package work.xiaohong.search.controller;

import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.*;
import org.elasticsearch.cluster.metadata.MappingMetadata;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import work.xiaohong.search.config.ElasticsearchConfig;
import work.xiaohong.search.entity.Result;
import work.xiaohong.search.entity.StatusCode;

import java.util.Map;

@RequestMapping("/mapping")
@RestController
public class MappingController {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Autowired
    private IndexController indexController;

    /**
     * 更新索引
     * @param index
     * @param mapping
     * @return
     * @throws Exception
     */
    @PutMapping("/{index}")
    private Result update(@PathVariable(name = "index") String index, @RequestBody Map<String,Map<String, Map<String,Object>>> mapping) throws Exception {
        PutMappingRequest request = new PutMappingRequest(index);

        if (indexController.exists(index).getData()){
            // 更新mapping
            request.source(mapping);
            AcknowledgedResponse response = restHighLevelClient.indices().putMapping(request, ElasticsearchConfig.COMMON_OPTIONS);
            if (response.isAcknowledged()){
                return new Result(false, StatusCode.OK,"更新索引Mapping成功");
            }else {
                return new Result(false, StatusCode.ERROR,"更新索引Mapping失败");
            }
        }else {
            // 新建
            return new Result(false, StatusCode.ERROR,"索引不存在");
        }
    }

    /**
     * 更新索引
     * @param index
     * @param mapping
     * @return
     * @throws Exception
     */
    @GetMapping("/{index}")
    private Result getMapping(@PathVariable(name = "index") String index, @RequestBody Map<String,Map<String, Map<String,Object>>> mapping) throws Exception {
        GetMappingsRequest request = new GetMappingsRequest();
        request.indices(index);

        if (indexController.exists(index).getData()){
            // 更新mapping
            GetMappingsResponse response = restHighLevelClient.indices().getMapping(request, ElasticsearchConfig.COMMON_OPTIONS);
            Map<String, MappingMetadata> allMappings = response.mappings();
            MappingMetadata indexMapping = allMappings.get(index);
            Map<String, Object> result = indexMapping.sourceAsMap();
            return new Result(false, StatusCode.OK,"获取索引Mapping成功",result);
        }else {
            // 新建
            return new Result(false, StatusCode.ERROR,"索引不存在");
        }
    }


}
